package org.inh.ld20.dangerousbrother.screen;

import java.awt.Graphics;

import org.inh.ld20.dangerousbrother.Art;
import org.inh.ld20.dangerousbrother.Camera;
import org.inh.ld20.dangerousbrother.Input;
import org.inh.ld20.dangerousbrother.Level;
import org.inh.ld20.dangerousbrother.entity.BigBrother;
import org.inh.ld20.dangerousbrother.entity.Entity;
import org.inh.ld20.dangerousbrother.entity.Entity.FacingDirection;

public class GameScreen extends Screen {
	
	Entity mainCharacter;
	Level level;
	Camera camera;
	
	public GameScreen() {
		camera = new Camera();
		
		// Init the game state
		level = new Level(camera);
		
		mainCharacter = new Entity(Art.mainCharacter);
		mainCharacter.x = 0;
		level.entities.add(mainCharacter);
		
		Entity follower1 = new Entity(Art.follower1);
		mainCharacter.follower = follower1;
		follower1.following = mainCharacter;
		level.entities.add(follower1);
		
		Entity follower2 = new Entity(Art.follower2);
		follower1.follower = follower2;
		follower2.following = follower1;
		level.entities.add(follower2);
	}

	@Override
	public void tick(Input input) {
		if(input.buttons[Input.LEFT]) {
			mainCharacter.facingDirection = Entity.FacingDirection.LEFT;
			mainCharacter.tryMove(level, -BigBrother.WALK_SPEED, 0);
		}
		if(input.buttons[Input.RIGHT]) {
			mainCharacter.facingDirection = Entity.FacingDirection.RIGHT;
			mainCharacter.tryMove(level, BigBrother.WALK_SPEED, 0);
		}
		
		level.tick(input);
	}

	@Override
	public void render(Graphics g) {
		//g.setColor(Color.WHITE);
		//g.fillRect(0,0,DangerousBrother.GAME_WIDTH, DangerousBrother.GAME_HEIGHT);
		
		level.draw(g);
		
		for(Entity e : level.entities) {
			// TODO entities should store animations instead of a single image,
			// and then the following drawing code should draw the current animation
			// frame.
			
			int screenX = (int) Math.round(e.x - camera.x*Level.TILE_SIZE);
			int screenY = (int) Math.round(e.y - camera.y*Level.TILE_SIZE);
			
			if(e.facingDirection == FacingDirection.LEFT) {
				// flip the image
				g.drawImage(e.animation.getCurrentFrame(), screenX, screenY, screenX+e.width, screenY+e.height, e.width, 0, 0, e.height, null);
			} else if(e.facingDirection == FacingDirection.RIGHT) {
				g.drawImage(e.animation.getCurrentFrame(), screenX, screenY, e.width, e.height, null);
			} else {
				throw new RuntimeException("Entity invalid facingdirection");
			}
		}
		
	}
	
}
